package com.skywolf.chem.manager.controller;


import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.aliyuncs.CommonResponse;
import com.skywolf.chem.common.context.LoginUser;
import com.skywolf.chem.common.context.RequestContext;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.manager.entity.PushMessage;
import com.skywolf.chem.manager.entity.PushMessageParam;
import com.skywolf.chem.manager.entity.PushMessageVo;
import com.skywolf.chem.manager.service.IPushMessageService;
import com.skywolf.chem.utils.SysConfig;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 消息推送表 前端控制器
 * </p>
 *
 * @author
 * @since 2020-07-13
 */
@Slf4j
@RestController
@RequestMapping("/manager/push-message")
public class PushMessageController {

    @Autowired
    IPushMessageService pushMessageService;


    @ApiOperation(value = "推送消息列表",notes = "推送消息列表")
    @RequestMapping(value = "/getPushMsgList",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PushMessage> getPushMsgList(@RequestBody @Validated PushMessageParam queryParam) {
        queryParam.setPushStatus(1);
        PageVO<PushMessage> page = pushMessageService.pushMsgListPage(queryParam);
        return RespData.success(page);
    }


    @ApiOperation(value = "推送消息",notes = "推送消息")
    @RequestMapping(value = "/pushMsg",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PushMessage> pushMsg(@RequestBody @Validated PushMessageVo msg) {
        String AppKey = SysConfig._this.getProperty("jpush.appkey");
        String MasterSecret = SysConfig._this.getProperty("jpush.secret");
        String title = msg.getPushTitle();  //标题
        String contents = msg.getPushMsg();  //内容
        if(StringUtils.isEmpty(MasterSecret) || StringUtils.isEmpty(AppKey)){
            return RespData.failure(ResponseCodeEnum.PUSH_CONFIG_ERROR);
        }
        PushResult pushResult = push(String.valueOf(title),contents,MasterSecret,AppKey,msg.getArticleId());
        PushMessage pushMessage = new PushMessage();pushMessage.setPushTitle(msg.getPushTitle());

        pushMessage.setPushMsg(msg.getPushMsg());
        pushMessage.setArticleId(msg.getArticleId());
        try{
            LoginUser user = RequestContext.getLoginUser();
            pushMessage.setCreatedBy(user.getId());
        }catch (Exception e){
            log.info("pushMsg 获取推送人信息异常！");
        }
        if(pushResult != null && pushResult.isResultOK()){
            log.info("针对别名" + title + "的信息推送成功！");
            pushMessage.setPushStatus(1);
            pushMessageService.save(pushMessage);
        }else {
            log.info("针对别名" + title + "的信息推送失败！");
            pushMessage.setPushStatus(0);
            pushMessageService.save(pushMessage);
            return RespData.failure(ResponseCodeEnum.PUSH_MSG_ERROR);
        }
        return RespData.success("success");
    }

    /**
     * 极光推送方法(采用java SDK)
     * @param title
     * @param contents
     * @return PushResult
     */
    public PushResult push(String title,String contents,String MasterSecret,String AppKey,Long id){
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(MasterSecret, AppKey, null, clientConfig);
        PushPayload payload = buildPushObject_android_ios_alias_alert(title,contents,id);
        try {
            return jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            return null;
        }
    }

    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * @param title
     * @param contents
     * @return PushPayload
     */
    public PushPayload buildPushObject_android_ios_alias_alert(String title, String contents,Long id){
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())//推送平台
                .setAudience(Audience.all())//推送目标
                .setNotification(Notification.newBuilder().addPlatformNotification(AndroidNotification.
                        newBuilder().addExtra("toPage","NewsDetail").addExtra("id",id).
                        setAlert(contents).setTitle(title).build()).build())//通知消息（标题，内容）
                .setOptions(Options.newBuilder().setApnsProduction(false).setTimeToLive(86400).build()//离线消息保存时间
                )
                .build();
    }
}
